'use server';

import type { Metadata } from 'next';
import './style.scss';
import { notFound } from 'next/navigation';
import { fetchDocument } from '@/lib/api/page/document';

export async function generateMetadata({ params }: { params: Promise<{ code: string }> }): Promise<Metadata> {
	const { code } = await params;
	const result = await fetchDocument(code);

	if (!result.success || !result.data) {
		return {
			title: '문서를 찾을 수 없음 - 개미투자'
		};
	}

	const doc = result.data;
	const plainText = doc.content
		? doc.content.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 160)
		: doc.subject;
	const canonicalUrl = `https://antooza.com/docs/${doc.code}`;

	return {
		title: `${doc.subject} - 개미투자`,
		description: plainText,
		alternates: { canonical: canonicalUrl },
		robots: { index: true, follow: true },
		openGraph: {
			title: doc.subject,
			description: plainText,
			url: canonicalUrl,
			type: 'article'
		}
	};
}

export default async function DocumentPage({ params }: { params: Promise<{ code: string }> }) {
	const { code } = await params;

	const result = await fetchDocument(code);

	if (!result.success || !result.data) {
		return notFound();
	}

	const doc = result.data;

	return (
		<>
			<article id='docs'>
				<h1>{doc.subject}</h1>
				{doc.content && (
					<section dangerouslySetInnerHTML={{ __html: doc.content }} className='pb-10'/>
				)}
			</article>
		</>
	);
}